<template>
  <div class="content">
    <div class="scroll-view-box">
      <projectMsg :projectId="project_id" :sjFile="true" :hrefProject="true"></projectMsg>

      <el-form :model="cjzjdRuleForm" :rules="cjzjdRules" ref="cjzjdRuleForm" label-position="top" label-width="120px"
        inline>
        <div class="user-title-box">基础信息</div>
        <el-form-item label="预计开工日期" prop="start_date">
          <el-date-picker class="input-width" v-model="cjzjdRuleForm.start_date" type="date" placeholder="选择日期"
            clearable value-format="yyyy-MM-dd" :picker-options="pickerOptionsEnd"
            @change="cjzjdDataFunc($event, 'start')">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预计完工日期" prop="end_date">
          <el-date-picker class="input-width" v-model="cjzjdRuleForm.end_date" type="date" clearable placeholder="选择日期"
            value-format="yyyy-MM-dd" :disabled="!cjzjdRuleForm.start_date" :picker-options="pickerOptions_"
            @change="cjzjdDataFunc($event, 'end')">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="cjzjdRuleForm.duration_days" label="工期天数" prop="duration_days">
          <el-input class="input-width" v-model="cjzjdRuleForm.duration_days" disabled clearable><span
              slot="suffix">天</span></el-input>
        </el-form-item>
        <el-form-item label="建筑面积" prop="building_area">
          <el-input class="input-width" placeholder="单位（m²）" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.building_area"></el-input>
        </el-form-item>
        <el-form-item label="报价类型" prop="is_first">
          <el-select filterable class="input-width" v-model="cjzjdRuleForm.is_first" placeholder="请选择">
            <el-option v-for="item in quotationTypeOptions" clearable :key="item.value" :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input :rows="1" class="input-width" v-model="cjzjdRuleForm.remark" type="textarea"></el-input>
        </el-form-item>
        <div class="user-title-box">报价金额</div>
        <el-form-item label="基础装修费" prop="basic_decoration_fee">
          <el-input class="input-width" @input="cjzjdInputChange" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.basic_decoration_fee"></el-input>
        </el-form-item>
        <el-form-item label="主材采购费" prop="material_costs">
          <el-input class="input-width" @input="cjzjdInputChange" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.material_costs"></el-input>
        </el-form-item>
        <el-form-item label="报价税金" prop="quotation_taxes">
          <el-input class="input-width" @input="cjzjdInputChange" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.quotation_taxes"></el-input>
        </el-form-item>
        <div class="user-title-box">成本金额</div>
        <el-form-item label="现场采购成本" prop="procurement_cost">
          <el-input class="input-width" @input="cjzjdInputChange" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.procurement_cost"></el-input>
        </el-form-item>
        <el-form-item label="公司集采成本" prop="centralized_procurement_cost">
          <el-input class="input-width" @input="cjzjdInputChange" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.centralized_procurement_cost"></el-input>
        </el-form-item>
        <el-form-item label="管理成本" prop="management_costs">
          <el-input class="input-width" @input="cjzjdInputChange" clearable v-input-limit="2"
            v-model="cjzjdRuleForm.management_costs"></el-input>
        </el-form-item>
        <div class="user-title-box">总计</div>
        <el-form-item label="报价金额" prop="quotation_amount">
          <el-input class="input-width" @input="cjzjdInputChange" clearable disabled v-input-limit="2"
            v-model="cjzjdRuleForm.quotation_amount"></el-input>
        </el-form-item>
        <el-form-item label="成本金额" prop="cost_amount">
          <el-input class="input-width" @input="cjzjdInputChange" clearable disabled v-input-limit="2"
            v-model="cjzjdRuleForm.cost_amount"></el-input>
        </el-form-item>
        <el-form-item label="利润金额" prop="profit_amount">
          <el-input class="input-width" clearable disabled v-input-limit="2"
            v-model="cjzjdRuleForm.profit_amount"></el-input>
        </el-form-item>
        <el-form-item label="利润率(报价)" prop="profit_ratio">
          <el-input class="input-width" clearable disabled v-input-limit="2" v-model="cjzjdRuleForm.profit_ratio"><span
              slot="suffix">%</span></el-input>
        </el-form-item>
        <div class="user-title-box">附件</div>
        <el-form-item label="报价单文件 (.ppt,.xls,.pdf,.doc,.docx,.xlsx)" prop="quotation_file" label-width="310px">
          <div class="file-list-box">
            <div class="file-item-box" v-for="(item, index) in cjzjdRuleForm.quotation_file" :key="index">
              <div class="el-icon-delete-box" @click="cjzjdFileRemove(index, 'quotation_file')">
                <i class="el-icon-error"></i>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.name" placement="top">
                <img class="img" :src="$fileImgFunc(item)" />
              </el-tooltip>
            </div>

            <el-upload accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx" class="avatar-uploader" action="#"
              :show-file-list="false" :auto-upload="false" list-type="picture-card" :on-change="(file, fileList) => {
                cjzjdChangeFile(file, fileList, 'quotation_file');
              }
                ">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="利润单文件 (.ppt,.xls,.pdf,.doc,.docx,.xlsx)" prop="profit_statement_file" label-width="310px">
          <div class="file-list-box">
            <div class="file-item-box" v-for="(item, index) in cjzjdRuleForm.profit_statement_file" :key="index">
              <div class="el-icon-delete-box" @click="cjzjdFileRemove(index, 'profit_statement_file')">
                <i class="el-icon-error"></i>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.name" placement="top">
                <img class="img" :src="$fileImgFunc(item)" />
              </el-tooltip>
            </div>

            <el-upload accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx" class="avatar-uploader" action="#"
              :show-file-list="false" :auto-upload="false" list-type="picture-card" :on-change="(file, fileList) => {
                cjzjdChangeFile(file, fileList, 'profit_statement_file');
              }
                ">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="工程量清单 (.ppt,.xls,.pdf,.doc,.docx,.xlsx)" prop="cost_list_file" label-width="310px">
          <div class="file-list-box">
            <div class="file-item-box" v-for="(item, index) in cjzjdRuleForm.cost_list_file" :key="index">
              <div class="el-icon-delete-box" @click="cjzjdFileRemove(index, 'cost_list_file')">
                <i class="el-icon-error"></i>
              </div>
              <el-tooltip class="item" effect="dark" :content="item.name" placement="top">
                <img class="img" :src="$fileImgFunc(item)" />
              </el-tooltip>
            </div>

            <el-upload accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx" class="avatar-uploader" action="#"
              :show-file-list="false" :auto-upload="false" list-type="picture-card" :on-change="(file, fileList) => {
                cjzjdChangeFile(file, fileList, 'cost_list_file');
              }
                ">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <template v-if="cjzjdRuleForm.hisFileList">
          <div class="user-title-box">历史附件</div>
          <el-form-item label="报价单文件" prop="" label-width="310px">
            <div class="file-list-box">
              <div class="file-item-box" v-for="(item, index) in cjzjdRuleForm.hisFileList.quotation_file" :key="index">
                <el-tooltip class="item" effect="dark" :content="item.file_name" placement="top">
                  <img class="img" :src="$fileImgFunc(item)" @click="$fileViewHandle(item)" />
                </el-tooltip>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="利润单文件" prop="" label-width="310px">
            <div class="file-list-box">
              <div class="file-item-box" v-for="(item, index) in cjzjdRuleForm.hisFileList.profit_statement_file"
                :key="index">
                <el-tooltip class="item" effect="dark" :content="item.file_name" placement="top">
                  <img class="img" :src="$fileImgFunc(item)" @click="$fileViewHandle(item)" />
                </el-tooltip>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="工程量清单" prop="" label-width="310px">
            <div class="file-list-box">
              <div class="file-item-box" v-for="(item, index) in cjzjdRuleForm.hisFileList.cost_list_file" :key="index">
                <el-tooltip class="item" effect="dark" :content="item.file_name" placement="top">
                  <img class="img" :src="$fileImgFunc(item)" @click="$fileViewHandle(item)" />
                </el-tooltip>
              </div>
            </div>
          </el-form-item>
        </template>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cjzjdSubmit('cjzjdRuleForm')" :disabled="diaLoading"
          :loading="diaLoading">提交</el-button>
        <el-button @click="cjzjdCancel('cjzjdRuleForm')">关闭</el-button>
      </span>
    </div>
  </div>
</template>
<script>
import projectApi from "@/api/projectApi";
import commonApi from "@/api/common";
import * as math from "mathjs";
import projectMsg from "@/components/ProjectMsg";

export default {
  name: "cjzjdCom",
  components: {
    projectMsg,
  },
  data() {
    var quotation_file = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请上传报价单文件"));
      } else {
        callback();
      }
    };
    var profit_statement_file = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请上传利润单文件"));
      } else {
        callback();
      }
    };
    var cost_list_file = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请上传成本单文件"));
      } else {
        callback();
      }
    };
    return {
      cjzjdRules: {
        start_date: {
          required: true,
          message: "请选择开工日期",
          trigger: "change",
        },
        end_date: {
          required: true,
          message: "请选择完工日期",
          trigger: "change",
        },
        duration_days: {
          required: true,
          message: "请输入工期天数",
          trigger: "change",
        },
        building_area: {
          required: true,
          message: "请输入建筑面积",
          trigger: "change",
        },
        quotation_amount: {
          required: true,
          message: "请输入报价金额",
          trigger: "change",
        },
        basic_decoration_fee: {
          required: true,
          message: "请输入基础装修费用",
          trigger: "change",
        },
        material_costs: {
          required: true,
          message: "请输入主材采购费用",
          trigger: "change",
        },
        quotation_taxes: {
          required: true,
          message: "请输入报价税金",
          trigger: "change",
        },
        cost_amount: {
          required: true,
          message: "请输入成本金额",
          trigger: "change",
        },
        procurement_cost: {
          required: true,
          message: "请输入现场采购成本",
          trigger: "change",
        },
        centralized_procurement_cost: {
          required: true,
          message: "请输入公司集采成本",
          trigger: "change",
        },
        management_costs: {
          required: true,
          message: "请输入管理成本",
          trigger: "change",
        },
        profit_amount: {
          required: true,
          message: "请输入利润金额",
          trigger: "change",
        },
        profit_ratio: {
          required: true,
          message: "请输入利润率(报价)",
          trigger: "change",
        },
        is_first: {
          required: true,
          message: "请选择报价类型",
          trigger: "change",
        },

        quotation_file: {
          required: true,
          validator: quotation_file,
          trigger: "change",
        },
        profit_statement_file: {
          required: true,
          validator: profit_statement_file,
          trigger: "change",
        },
        cost_list_file: {
          required: true,
          validator: cost_list_file,
          trigger: "change",
        },
        remark: "",
      },
      cjzjdRuleForm: {
        start_date: "",
        end_date: "",
        duration_days: "",
        building_area: "",
        quotation_amount: "",
        basic_decoration_fee: "",
        material_costs: "",
        quotation_taxes: "",
        cost_amount: "",
        procurement_cost: "",
        centralized_procurement_cost: "",
        management_costs: "",
        profit_amount: "",
        is_first: 1,
        quotation_file: [],
        profit_statement_file: [],
        cost_list_file: [],
        profit_ratio: "",
        remark: "",
      },
      pickerOptionsStart: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      pickerOptionsEnd: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      pickerOptions_: {},
      quotationTypeOptions: [
        {
          value: 1,
          label: "首次报价",
        },
        {
          value: 2,
          label: "调整报价",
        },
        // {
        //   value: 3,
        //   label: "增减项施工报价",
        // },
      ],
      diaLoading: false,
      project_id: "",
      dataObj: ''
    };
  },
  computed: {},
  mounted() {
    this.project_id = this.$route.query.id;
    this.getProjectLog();//项目日志
    this.selectProjectDetails();//项目基本信息
  },
  methods: {
    // 获取项目基本信息
    selectProjectDetails() {
      commonApi.selectProjectDetails({
        project_id: this.project_id
      }).then(res => {
        console.log(res, "获取项目基础信息")
        if (res.code == 200) {
          this.dataObj = res.data;
        }
      })
    },
    cjzjdCancel(formName) {
      this.$goBackTab(this);
    },
    cjzjdDataFunc(e, type) {
      let cjzjdRuleForm = this.cjzjdRuleForm;
      if (type == "start") {
        if (cjzjdRuleForm.start_date) {
          this.pickerOptions_ = {
            disabledDate(time) {
              return (
                time.getTime() < new Date(cjzjdRuleForm.start_date).getTime()
              );
            },
          };
        } else {
          cjzjdRuleForm.end_date = "";
        }
      }
      if (cjzjdRuleForm.start_date && cjzjdRuleForm.end_date) {
        const date1 = new Date(cjzjdRuleForm.start_date);
        const date2 = new Date(cjzjdRuleForm.end_date);
        if (!this.compareDates(date1, date2)) {
          this.$message.warning("完工日期需晚于开工日期");
          type == "start"
            ? (cjzjdRuleForm.start_date = "")
            : (cjzjdRuleForm.end_date = "");
          cjzjdRuleForm.duration_days = "";
          this.cjzjdRuleForm = cjzjdRuleForm;
          return;
        }
        cjzjdRuleForm.duration_days = this.daysBetween(date1, date2) + 1;
      } else {
        cjzjdRuleForm.duration_days = "";
      }
      this.cjzjdRuleForm = cjzjdRuleForm;
    },
    cjzjdSubmit(formName) {
      let cjzjdRuleForm = this.cjzjdRuleForm;
      console.log(cjzjdRuleForm, "出具造价单参数");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formdata = new FormData();
          formdata.append(
            "data",
            JSON.stringify({
              project_id: this.project_id,
              remark: cjzjdRuleForm.remark,
              start_date: cjzjdRuleForm.start_date,
              end_date: cjzjdRuleForm.end_date,
              duration_days: cjzjdRuleForm.duration_days,
              building_area: cjzjdRuleForm.building_area,
              quotation_amount: cjzjdRuleForm.quotation_amount,
              basic_decoration_fee: cjzjdRuleForm.basic_decoration_fee,
              material_costs: cjzjdRuleForm.material_costs,
              quotation_taxes: cjzjdRuleForm.quotation_taxes,
              cost_amount: cjzjdRuleForm.cost_amount,
              procurement_cost: cjzjdRuleForm.procurement_cost,
              centralized_procurement_cost:
                cjzjdRuleForm.centralized_procurement_cost,
              management_costs: cjzjdRuleForm.management_costs,
              profit_amount: cjzjdRuleForm.profit_amount,
              is_first: cjzjdRuleForm.is_first,
              quotation_type: 1,
              profit_ratio: cjzjdRuleForm.profit_ratio,
            })
          );
          cjzjdRuleForm.quotation_file.forEach((item) => {
            formdata.append("quotation_file[]", item.raw);
          });
          cjzjdRuleForm.profit_statement_file.forEach((item) => {
            formdata.append("profit_statement_file[]", item.raw);
          });
          cjzjdRuleForm.cost_list_file.forEach((item) => {
            formdata.append("cost_list_file[]", item.raw);
          });
          this.diaLoading = true;
          projectApi
            .issueQuotation(formdata)
            .then((res) => {
              console.log(res, "出具造价单");
              this.diaLoading = false;
              if (res.code == 200) {
                this.cjzjdCancel();
              }
              this.$message({
                type: res.code == 200 ? "success" : "warning",
                message: res.code == 200 ? "处理成功" : res.message,
              });
            })
            .catch((err) => {
              this.diaLoading = false;
              this.$message({
                type: "warning",
                message: err.message,
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    cjzjdChangeFile(file, fileList, type) {
      let cjzjdRuleForm = this.cjzjdRuleForm;
      cjzjdRuleForm[type] = [file];
      this.cjzjdRuleForm = cjzjdRuleForm;
    },
    cjzjdFileRemove(index, type) {
      let cjzjdRuleForm = this.cjzjdRuleForm;
      cjzjdRuleForm[type] = [];
      this.cjzjdRuleForm = cjzjdRuleForm;
    },
    cjzjdInputChange() {
      // 金额计算
      let cjzjdRuleForm = this.cjzjdRuleForm;
      let basic_decoration_fee = cjzjdRuleForm.basic_decoration_fee || 0; //基础装修费
      let material_costs = cjzjdRuleForm.material_costs || 0; ///主材采购费用
      let quotation_taxes = cjzjdRuleForm.quotation_taxes || 0; //报价税金
      // 计算报价金额（基础装修费用+主材采购+报价税金）
      let quotation_amount = 0; //报价金额
      quotation_amount = math.format(
        math.add(
          math.bignumber(basic_decoration_fee),
          math.bignumber(material_costs),
          math.bignumber(quotation_taxes)
        )
      );
      quotation_amount = ((quotation_amount * 100) / 100).toFixed(2);
      cjzjdRuleForm.quotation_amount = quotation_amount;

      // 计算成本（现场采购+公司采集+管理成本）
      let procurement_cost = cjzjdRuleForm.procurement_cost || 0; //现场采购成本
      let centralized_procurement_cost =
        cjzjdRuleForm.centralized_procurement_cost || 0; //公司集采成本
      let management_costs = cjzjdRuleForm.management_costs || 0; //管理成本
      let cost_amount = 0; //成本金额
      cost_amount = math.format(
        math.add(
          math.bignumber(procurement_cost),
          math.bignumber(centralized_procurement_cost),
          math.bignumber(management_costs),
          math.bignumber(quotation_taxes)
        )
      );
      cost_amount = ((cost_amount * 100) / 100).toFixed(2);
      cjzjdRuleForm.cost_amount = cost_amount;

      // 计算利润金额 报价-（现场采购+公司采集+管理+税金）
      let profit_amount = 0; //利润金额
      let profit_ratio = 0; //利润率
      let all_costs = 0; //总成本
      all_costs = math.format(
        math.add(
          math.bignumber(procurement_cost),
          math.bignumber(centralized_procurement_cost),
          math.bignumber(management_costs),
          math.bignumber(quotation_taxes)
        )
      );
      all_costs = Number(all_costs).toFixed(2); //总成本
      profit_amount = math.format(
        math.subtract(
          math.bignumber(quotation_amount),
          math.bignumber(all_costs)
        )
      );
      profit_amount = Number(profit_amount).toFixed(2);
      cjzjdRuleForm.profit_amount = profit_amount;

      // 计算利润率(报价-成本/成本)*100
      if (Number(quotation_amount) && Number(cost_amount)) {
        profit_ratio = math.format(
          math.subtract(math.bignumber(quotation_amount), math.bignumber(cost_amount))
        )
        profit_ratio = math.format(
          math.divide(math.bignumber(profit_ratio), math.bignumber(cost_amount))
        )
        profit_ratio = Number((profit_ratio * 100).toFixed(2));
        cjzjdRuleForm.profit_ratio = profit_ratio;
      }

      this.cjzjdRuleForm = cjzjdRuleForm;
    },
    compareDates(date1, date2) {
      return date1.getTime() - date2.getTime() < 0;
    },
    daysBetween(date1, date2) {
      const oneDay = 24 * 60 * 60 * 1000; // 每天的毫秒数
      const firstTime = date1.getTime();
      const secondTime = date2.getTime();

      return Math.round(Math.abs((firstTime - secondTime) / oneDay));
    },
    // 获取项目日志
    getProjectLog() {
      this.logList = [];
      projectApi
        .getProjectLogList({
          project_id: this.$route.query.id,
          // log_type: Number(this.activeName),
        })
        .then((res) => {
          console.log(res, "项目日志");
          if (res.code == 200) {
            res.data.forEach((item) => {
              if (item.form_data) {
                item.form_data = JSON.parse(item.form_data);
              }
              // 拿到最近一条历史造价单（再次造价时用,审核用）
              if (item.log_status == 220 && !this.hisQuotationData) {
                let hisQuotationData = item.form_data;
                console.log(hisQuotationData, "历史造价单")
                this.cjzjdRuleForm = {
                  start_date: hisQuotationData.start_date,
                  end_date: hisQuotationData.end_date,
                  duration_days: hisQuotationData.duration_days,
                  building_area: hisQuotationData.building_area,
                  quotation_amount: hisQuotationData.quotation_amount,
                  basic_decoration_fee: hisQuotationData.basic_decoration_fee,
                  material_costs: hisQuotationData.material_costs,
                  quotation_taxes: hisQuotationData.quotation_taxes,
                  cost_amount: hisQuotationData.cost_amount,
                  procurement_cost: hisQuotationData.procurement_cost,
                  centralized_procurement_cost:
                    hisQuotationData.centralized_procurement_cost,
                  management_costs: hisQuotationData.management_costs,
                  profit_amount: hisQuotationData.profit_amount,
                  is_first: 2,
                  quotation_type: 1,
                  quotation_file: [],
                  profit_statement_file: [],
                  cost_list_file: [],
                  profit_ratio: hisQuotationData.profit_ratio,
                  remark: hisQuotationData.remark,
                  hisFileList: {
                    cost_list_file: hisQuotationData.cost_list_file,
                    profit_statement_file: hisQuotationData.profit_statement_file,
                    quotation_file: hisQuotationData.quotation_file,
                  }
                };
                this.hisQuotationData = hisQuotationData;
              }
              // 拿到申请报价的开工，完工日期。填充给造价员造价
              if (item.log_status == 200 && !this.startEndDate) {
                let startEndDate = {
                  start_date: item.form_data.start_date,
                  end_date: item.form_data.end_date,
                };
                this.cjzjdRuleForm.start_date = startEndDate.start_date;
                this.cjzjdRuleForm.end_date = startEndDate.end_date;
                const date1 = new Date(startEndDate.start_date);
                const date2 = new Date(startEndDate.end_date);
                this.cjzjdRuleForm.duration_days =
                  this.daysBetween(date1, date2) + 1;
              }
            });
          }
        })
        .catch((err) => {
          this.logLoaidng = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/addPage.scss";
</style>